package com.leyou.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zqq
 * @ClassName IpUtil
 * @Description
 * @date 2020/3/24-14:40
 */
public class IpUtil {

    /**
     * @Title: getIp
     * @Description: 获取客服端真实IP地址
     * @author: zqq
     * @param request
     * @return: java.lang.String
     * @createTime: 2020-03-24 14:41
     * @version: v.1.0
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}
